package org.teammach.laddercomp.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.teammach.laddercomp.shared.BlogEntry;
import org.teammach.laddercomp.shared.OfficialLadder;

import com.google.appengine.api.datastore.KeyFactory;

public enum BlogManager {

	INSTANCE;
	
	public BlogEntry getLatestBlog() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(BlogEntry.class);
		query.setOrdering("created desc");
		query.setRange("0,1");
		query.setFilter("deleted == false");
		List<BlogEntry> entries = (List<BlogEntry>) query.execute();
		entries.size();

		pm.close();
		if(entries.size() > 0)
			return entries.get(0);
		return null;
	}
	
	public List<BlogEntry> getAllBlogs() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(BlogEntry.class);
		query.setOrdering("created desc");
		query.setFilter("deleted == false");

		List<BlogEntry> entries = (List<BlogEntry>) query.execute();
		entries.size();

//		for(BlogEntry entry : entries) {
//			if(entry.getDeleted() == null) {
//				entry.setDeleted(false);
//				pm.makePersistent(entry);
//			}
//		}
		pm.close();
		return entries;
	}
	
	public void addBlogEntry(String title, String content) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		BlogEntry newBlog = new BlogEntry(title, content);
		pm.makePersistent(newBlog);
		pm.close();
	}
	
	public void deleteAllBlogs() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(BlogEntry.class);
		List<BlogEntry> entries = (List<BlogEntry>) query.execute();
		for(BlogEntry entry : entries) {
			pm.deletePersistent(entry);
		}
		pm.close();
		
	}
	
	public void updateBlog(String key, String title, String content){
		PersistenceManager pm = PMF.get().getPersistenceManager();

		BlogEntry entry = (BlogEntry)pm.getObjectById(BlogEntry.class, KeyFactory.stringToKey(key));
		entry.setTitle(title);
		entry.setContent(content);
		pm.makePersistent(entry);
		pm.close();
	}
	
	public void deleteBlog(String key){
		PersistenceManager pm = PMF.get().getPersistenceManager();

		BlogEntry entry = (BlogEntry)pm.getObjectById(BlogEntry.class, KeyFactory.stringToKey(key));
		entry.setDeleted(true);
		pm.makePersistent(entry);
		pm.close();
	}
}
